package cn.chenxinjie.hrm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * @author 陈鑫杰
 * @date 2022/3/21 18:57
 */
@EnableAuthorizationServer // 声明为认证授权服务方
@Configuration
public class HrmAuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    /**
     * 授权服务安全配置：配置哪些路径放行(检查token的路径要放行)
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 对应/oauth/check_token,路径公开
        security.checkTokenAccess("permitAll()")
                // 对应/oauth/token_key公开
                .tokenKeyAccess("permitAll()")
                // 允许客户端进行表单身份验证,使用表单认证申请令牌
                .allowFormAuthenticationForClients();
    }


    @Autowired
    private DataSource dataSource;
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 客户端详情：配置客户端请求的参数
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
    }

    private JdbcClientDetailsService clientDetailsService() {
        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        clientDetailsService.setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }


    @Autowired
    private AuthenticationManager authenticationManager;
    /**
     * 授权服务端点：配置授权码和令牌的管理/存储方式
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 1.密码授权模式需要
        endpoints.authenticationManager(authenticationManager)
                // 2.授权码模式服务
                .authorizationCodeServices(authorizationCodeServices())
                // 3.配置令牌管理服务
                .tokenServices(tokenService())
                // 允许post和get方式请求
                .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET);
    }

    /**
     * 获取令牌管理服务
     *
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        // 指定客户端详情配置
        tokenServices.setClientDetailsService(clientDetailsService());
        // 支持产生刷新token
        tokenServices.setSupportRefreshToken(true);
        // token存储方式
        //tokenServices.setTokenStore(new InMemoryTokenStore());
        tokenServices.setTokenStore(getJwtTokenStore());

        tokenServices.setAccessTokenValiditySeconds(350);

        // 设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        tokenServices.setTokenEnhancer(tokenEnhancerChain);  // jwtAccessTokenConverter()
        return tokenServices;
    }

    private static final String key = "chenxinjie";
    /**
     * jwt token转换器
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 设置密钥 (盐值)
        jwtAccessTokenConverter.setSigningKey(key);
        return jwtAccessTokenConverter;
    }

    /**
     * 获取jwtTokenStore
     *
     * @return
     */
    @Bean
    public TokenStore getJwtTokenStore() {
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore;
    }

    public AuthorizationCodeServices authorizationCodeServices(){
        return new JdbcAuthorizationCodeServices(dataSource);
    }
}
